﻿package net.wangit.view.tree;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.JDBCException;
import net.wangit.jdbc.ServerAccessException;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.util.Checker;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class TreeConfigFactory {

	private static Log log = LogFactory
			.getLog(net.wangit.view.tree.TreeConfigFactory.class);
	private static final String SQL = "select * from TREECONFIG where tid=?";

	public TreeConfigFactory() {
	}

	public static TreeConfig getTreeConfig(String domain, String treeId) {
		TreeConfig config = TreeConfigCache.get(domain, treeId);
		if (config == null) {
			config = createTreeConfig(domain, treeId);
			TreeConfigCache.put(domain, treeId, config);
		}
		return config;
	}

	private static TreeConfig createTreeConfig(String domain, String treeId) {
		DB db = DBHelper.getDomainDB(domain);
		MapList list = null;
		try {
			list = db.query(TreeConfigFactory.SQL, treeId, 2);
		} catch (JDBCException e) {
			log.error((new StringBuilder(
					"could not query tree'config in server: ")).append(domain)
					.toString(), e);
			throw new ServerAccessException((new StringBuilder(
					"could not query tree'config in server: ")).append(domain)
					.toString());
		}
		if (Checker.isEmpty(list)) {
			log.error((new StringBuilder("tree not found: ")).append(domain)
					.append("/").append(treeId).toString());
			throw new TreeConfigurationException((new StringBuilder(
					"tree not found: ")).append(domain).append("/").append(
					treeId).toString());
		} else {
			Row row = list.getRow(0);
			TreeConfig config = new TreeConfig();
			config.setDomain(domain);
			config.setTreeId(row.get("tid"));
			config.setFactory(row.get("fa"));
			config.setWriter(row.get("w"));
			config.setType(row.getInt("t", 1));
			config.setSkin(row.get("s"));
			config.setCacheEnabled("1".equals(row.get("c")));
			config.setDivAttribute(row.get("dc"));
			config.setImagePath(row.get("ip"));
			config.setDefaultTarget(row.get("dt"));
			config.setDefaultOpen("1".equals(row.get("do")));
			config.setShowLines(!"0".equals(row.get("sl")));
			config.setShowIcons(!"0".equals(row.get("si")));
			config.setSupportCheck("1".equals(row.get("sc")));
			config.setSupportCheckAll("1".equals(row.get("sca")));
			config.setSupportMove("1".equals(row.get("sm")));
			config.setSupportAdd("1".equals(row.get("sa")));
			config.setMoveBeforeInterceptor(row.get("mb"));
			config.setMoveAfterInterceptor(row.get("ma"));
			config.setFilter("1".equals(row.get("f")));
			return config;
		}
	}

}
